package com.senseauto.ffmepgcmd;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.UiModeManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;



import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;

/**
 * 录制的视频，需要手动修改视频大小尺寸，想通过ffmpeg命令来调整视频打开，ffmpeg的库的例子
 */
public class MainActivity extends AppCompatActivity {
    public static String TAG = "MainActivity";
    private ExecutorService ffmpegExecutor = null;

    private String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE ,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    private List<String> mPermissionList = new ArrayList<>();
    private int PERMISSION_REQUEST_CODE = 100;

    private boolean hasAllPermission() {
        mPermissionList.clear();
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        return mPermissionList.size() <= 0;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }

            if (hasPermissionDismiss) {
                Toast.makeText(this, "请授予必要权限", Toast.LENGTH_SHORT).show();

            } else {
            }
        }
    }
    MyRxFFmpegSubscriber myRxFFmpegSubscriber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ffmpegExecutor = new ThreadPoolExecutor(4, 8,
                60000L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        if (!hasAllPermission()) {
            ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST_CODE);
        }else{ //第一次赋值过权限后，第二次打开界面
            //startCamera();
        }
        File saveDir = new File(AutoApplication.getContext().getExternalFilesDir(null), "media_code_files_resize");
        Log.e(TAG, "saveDir:"+saveDir.getAbsolutePath());
        findViewById(R.id.btnConvert).setOnClickListener(v->{
            //先手动push一个视频到这个目录下
            String path = "/storage/emulated/0/Pictures/video_ir_2024_12_23_15_13_04.mp4";
            File file = new File(path);
            //ir视频录制的尺寸是3200*1800，需要裁剪为2592*1800的大小 如果初始界面传来的尺寸是1920*1080 这里也没必要采集视频
            if(file.exists() && file.length()>0 ){ //这个尺寸才是录制的3200*1800的视频
                File dir = null;
                UiModeManager uiModeManager = (UiModeManager) AutoApplication.getContext().getSystemService(Context.UI_MODE_SERVICE);
                if(uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR){ //（8295 开发板）
                    dir = new File(AutoApplication.getContext().getDataDir(),"media_code_files_resize");// getDataDir()对应路径 /data/user/10/com.senseauto.datacollectapp/
                }else{ //平板上
                    dir = new File(AutoApplication.getContext().getExternalFilesDir(null), "media_code_files_resize");
                }
                if(dir!=null && !dir.exists()){
                    dir.mkdirs();
                }
                String fileName = file.getName();
                File saveFile = new File(dir, fileName);
                try{
                    saveFile.createNewFile();
                }catch(Exception e){
                    e.printStackTrace();
                }
                Log.e(TAG, "ffmpeg scale video save:" + saveFile.getAbsolutePath());

                ffmpegExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        //这里需要加一个-y的参数，不然在平板手机上执行命令会报错，电脑上可以不加这个-y
                        String mergeCmd = String.format("ffmpeg -i %s -vf scale=2592:1800 -y %s", path, saveFile.getAbsolutePath());
                        Log.e(TAG, "scale video cmd:" + mergeCmd);

                        String[] commands = mergeCmd.split(" ");
                        int ret1 = RxFFmpegInvoke.getInstance().runFFmpegCmd(commands);
                        Log.e(TAG, "mergeCmd: " + mergeCmd + " ret: " + ret1);
                        //myRxFFmpegSubscriber = new MyRxFFmpegSubscriber(MainActivity.this);

                        //开始执行FFmpeg命令
                        /*RxFFmpegInvoke.getInstance()
                                .runCommandRxJava(commands)
                                .subscribe(myRxFFmpegSubscriber);*/

                    }

                });
            }else{
                Log.e(TAG, "file not exits");
            }

        });
    }


    public static class MyRxFFmpegSubscriber extends RxFFmpegSubscriber {

        private WeakReference<MainActivity> mWeakReference;

        public MyRxFFmpegSubscriber(MainActivity homeFragment) {
            mWeakReference = new WeakReference<>(homeFragment);
        }

        @Override
        public void onFinish() {
            Log.e(TAG, "onFinish");

        }

        @Override
        public void onProgress(int progress, long progressTime) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(String message) {
            Log.e(TAG, "onError:"+message);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myRxFFmpegSubscriber != null) {
            myRxFFmpegSubscriber.dispose();
        }
    }
}